package com.test20_多线程应用;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 竞拍抢答
 * 面试题：要求设置三个抢答者，而后同时发出抢答指令，抢答成功者给出成功提示，未抢答成功者给出失败提示。
 */
public class YootkDemo_03 {

    public static void main(String[] args) throws Exception {
        AnswerThread answerThread = new AnswerThread();
        FutureTask<String> taskA = new FutureTask<>(answerThread);
        FutureTask<String> taskB = new FutureTask<>(answerThread);
        FutureTask<String> taskC = new FutureTask<>(answerThread);
        new Thread(taskA, "抢答者A").start();
        new Thread(taskB, "抢答者B").start();
        new Thread(taskC, "抢答者C").start();
        System.out.println(taskA.get());
        System.out.println(taskB.get());
        System.out.println(taskC.get());
    }
}

class AnswerThread implements Callable<String> {
    private boolean flag;   // 抢答结果状态

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        synchronized (this) {
            if (this.flag == false) {   // 现在可以抢答
                this.flag = true;
                return "【" + Thread.currentThread().getName() + "】恭喜，抢答成功！！！";
            } else {
                return "【" + Thread.currentThread().getName() + "】遗憾，抢答失败！！！";
            }
        }
    }
}
